package com.car.carcontrol.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.widget.Toast;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

public class callMenu {
    String packageName;
    String targetAct;
    String menuName;

    private static Process process;

    /**
     * 结束进程,执行操作调用即可
     *前往/Users/pauljin/Library/Android/sdk
     *
     * sdk\builds-tools\
     * aapt dump badging  pk
     * package: name='
     *launchable-activity: name
     */
    public static void kill(String packageName) {
        int xx = initProcess();
        if(xx == 2) {
            killProcess(packageName);
            close();
        }
    }

    public static void toast(Context cx ,String msg) {
        Toast.makeText(cx, msg, Toast.LENGTH_SHORT).show();
    }
    /**
     * 初始化进程
     */
    private static int initProcess() {
        int tmp = 0;
        if (process == null)
            try {
                process = Runtime.getRuntime().exec("su");
                tmp = 2;
            } catch (IOException e) {
              //  e.printStackTrace();
                tmp = 1;
            }
        return  tmp;
    }

    /**
     * 结束进程
     */
    private static void killProcess(String packageName) {
        OutputStream out = process.getOutputStream();
        String cmd = "am force-stop " + packageName + " \n";
        try {
            out.write(cmd.getBytes());
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

   public static void closeAPk(String packName, Context context) {

       ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
       List<ActivityManager.RunningAppProcessInfo> infos = am.getRunningAppProcesses();
       for (ActivityManager.RunningAppProcessInfo info : infos) {
           if (info.processName.equals(packName)) {
               android.os.Process.killProcess(info.pid);
           }
       }
   }

    /**
     * 关闭输出流
     */
    private static void close() {
        if (process != null)
            try {
                process.getOutputStream().close();
                process = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

}
